<template>
  <div class="d-flex flex align-items-center w-100 justify-content-between">
    <div class="d-flex flex align-items-center">
      <i class="fa fa-fw text-muted mr-2 d-print-none" :class="attachData.viewIcon"></i>
      <div
        v-if="attachData.viewType === 'image'"
        type="text"
        class="px-0 text-primary"
        @click="handlePreviewFile"
      >
        {{ attachData.name }}
      </div>
      <div
        v-else-if="attachData.viewType === 'office'"
        type="text"
        class="px-0 text-primary"
        @click="handlePreviewOffice"
      >
        {{ attachData.name }}
      </div>
      <a
        v-else
        :href="urlTimeout(attachData.attachment || '')"
        target="_blank"
        :download="attachData.name"
      >
        {{ attachData.name }}
      </a>

      <div class="ml-3">
        <small class="text-primary">{{ attachData.create_time }}</small>
      </div>
    </div>
    <el-button class="d-print-none" type="text" @click="handleDownloadFile">下载</el-button>
  </div>
</template>

<script>
import { exportUrl } from '@/common/api/download'
import { downloadByLink } from '@vimi/utils-tool'
import { officePreview } from '@/common/plugins/tools/dom'

export default {
  components: {},
  props: {
    attachData: {
      type: Object,
      required: true,
    },
    attachList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      windowObjectReference: null,
    }
  },
  computed: {
    images() {
      const { attachment: url, name } = this.attachData
      return this.attachList.length
        ? this.attachList
            .filter(attach => attach.viewType === 'image')
            .map(attach => ({ url: attach.attachment, name: attach.name }))
        : [{ url, name }]
    },
    index() {
      const index = this.images.findIndex(attach => attach.url === this.attachData.attachment)
      return index < 0 ? 0 : index
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 图片预览
    handlePreviewFile() {
      this.$utils.viewer({
        images: this.images,
        index: this.index,
      })
    },

    // 文件下载
    async handleDownloadFile() {
      const { attachment: url, name } = this.attachData
      try {
        await exportUrl({ url: `${this.urlTimeout(url || '')}`, filename: name })
      } catch (error) {
        downloadByLink({ url: `${this.urlTimeout(url || '')}`, filename: name })
      }
    },

    // office预览
    handlePreviewOffice() {
      if (this.windowObjectReference !== null && !this.windowObjectReference.closed) {
        this.windowObjectReference.close()
      }

      this.windowObjectReference = officePreview({
        url: this.urlTimeout(this.attachData.attachment || ''),
      })
    },
    urlTimeout(url = '') {
      return url.includes('?') ? url : url + `?${+new Date()}`
    },
  },
}
</script>

<style lang="scss" scoped></style>
